<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文档表ID" prop="documentId">
        <el-input
          v-model="queryParams.documentId"
          placeholder="请输入文档表ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文档来源" prop="documentSource">
        <el-input
          v-model="queryParams.documentSource"
          placeholder="请输入文档来源"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传用户" prop="uploadUser">
        <el-input
          v-model="queryParams.uploadUser"
          placeholder="请输入上传用户"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:document:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:document:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:document:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:document:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="documentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文档表ID" align="center" prop="documentId" />
      <el-table-column label="文档来源" align="center" prop="documentSource">
        <template #default="scope">
          <el-link type="primary" @click="handlePreview(scope.row)">
            {{ getFileName(scope.row.filePath) }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="上传用户" align="center" prop="uploadUser" />
      <el-table-column label="文档类型" align="center" prop="documentType">
        <template #default="scope">
          <dict-tag :options="sys_file_type" :value="scope.row.documentType"/>
        </template>
      </el-table-column>
      <el-table-column label="文档关联数量" align="center" prop="relationCount" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:document:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:document:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文档管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="documentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文档来源" prop="documentSource">
          <el-input v-model="form.documentSource" placeholder="请输入文档来源" />
        </el-form-item>
        <el-form-item label="上传用户" prop="uploadUser">
          <el-input v-model="form.uploadUser" placeholder="请输入上传用户" />
        </el-form-item>
        <el-form-item label="文件存储地址" prop="filePath">
          <file-upload 
            v-model="form.filePath"
            :fileType="['doc', 'docx', 'ppt', 'pptx', 'txt', 'png', 'jpg', 'jpeg', 'xls', 'xlsx']"
            :isImage="false"
            :limit="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="文档预览"
      width="80%"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="preview-content">
        <!-- PDF预览 -->
        <pdf-viewer v-if="fileType === 'pdf'" :url="previewUrl" />
        <!-- Word文档预览 -->
        <div v-else-if="fileType === 'doc'" class="doc-preview" v-html="docContent"></div>
        <!-- PPT预览 -->
        <div v-else-if="fileType === 'ppt'" class="ppt-preview">
          <div class="unsupported-file">
            PPT文件暂不支持在线预览，请下载后查看
          </div>
        </div>
        <!-- Excel预览 -->
        <div v-else-if="fileType === 'excel'" class="excel-preview" v-html="docContent"></div>
        <!-- 图片预览 -->
        <div v-else-if="fileType === 'image'" class="image-preview">
          <img :src="previewUrl" alt="图片预览" />
        </div>
        <!-- 文本文件预览 -->
        <pre v-else-if="fileType === 'txt'" class="text-preview">{{ fileContent }}</pre>
        <!-- 不支持的文件类型 -->
        <div v-else class="unsupported-file">
          不支持预览该类型的文件
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Document">
import { listDocument, getDocument, delDocument, addDocument, updateDocument } from "@/api/system/document";
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import mammoth from 'mammoth';
import * as XLSX from 'xlsx';
import PdfViewer from '@/components/PdfViewer/index.vue';

const { proxy } = getCurrentInstance();
const { sys_file_type } = proxy.useDict('sys_file_type');

const documentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const previewVisible = ref(false);
const previewUrl = ref('');
const fileContent = ref('');
const docContent = ref('');

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    documentId: null,
    documentSource: null,
    uploadUser: null,
  },
  rules: {
    documentSource: [
      { required: true, message: "文档来源不能为空", trigger: "blur" }
    ],
    uploadUser: [
      { required: true, message: "上传用户不能为空", trigger: "blur" }
    ],
    documentType: [
      { required: true, message: "文档类型不能为空", trigger: "change" }
    ],
    filePath: [
      { required: true, message: "文件存储地址不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询文档管理列表 */
function getList() {
  loading.value = true;
  listDocument(queryParams.value).then(response => {
    documentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    documentId: null,
    documentSource: null,
    uploadUser: null,
    documentType: null,
    filePath: null,
    relationCount: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("documentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.documentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文档管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _documentId = row.documentId || ids.value
  getDocument(_documentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文档管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["documentRef"].validate(valid => {
    if (valid) {
      if (form.value.documentId != null) {
        updateDocument(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDocument(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _documentIds = row.documentId || ids.value;
  proxy.$modal.confirm('是否确认删除文档管理编号为"' + _documentIds + '"的数据项？').then(function() {
    return delDocument(_documentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/document/export', {
    ...queryParams.value
  }, `document_${new Date().getTime()}.xlsx`)
}

// 文件类型判断
const fileType = computed(() => {
  if (!previewUrl.value) return '';
  const ext = previewUrl.value.split('.').pop().toLowerCase();
  switch (ext) {
    case 'doc': return 'doc';
    case 'docx': return 'doc';
    case 'ppt': return 'ppt';
    case 'pptx': return 'ppt';
    case 'txt': return 'txt';
    case 'png': return 'image';
    case 'jpg': return 'image';
    case 'jpeg': return 'image';
    case 'xls':
    case 'xlsx': return 'excel';
    default: return '';
  }
});

// 添加获取文件名的函数
const getFileName = (filePath) => {
  if (!filePath) return '';
  // 移除查询参数（如果有）
  const pathWithoutQuery = filePath.split('?')[0];
  // 获取路径中的最后一部分作为文件名
  return pathWithoutQuery.split('/').pop();
};

// 修改处理预览函数
const handlePreview = async (row) => {
  if (!row.filePath) {
    ElMessage.warning('文件路径不存在');
    return;
  }
  
  // 检查文件路径是否已经包含完整的URL
  previewUrl.value = row.filePath.startsWith('http') 
    ? row.filePath 
    : import.meta.env.VITE_APP_BASE_API + row.filePath;
  
  try {
    if (fileType.value === 'txt') {
      const response = await fetch(previewUrl.value);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      fileContent.value = await response.text();
    } else if (fileType.value === 'doc') {
      const response = await fetch(previewUrl.value);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const arrayBuffer = await response.arrayBuffer();
      const result = await mammoth.convertToHtml({ arrayBuffer });
      docContent.value = result.value;
    } else if (fileType.value === 'excel') {
      const response = await fetch(previewUrl.value);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const arrayBuffer = await response.arrayBuffer();
      const workbook = XLSX.read(arrayBuffer, { type: 'array' });
      const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
      const htmlTable = XLSX.utils.sheet_to_html(firstSheet);
      docContent.value = htmlTable;
    }
    previewVisible.value = true;
  } catch (error) {
    console.error('文件加载失败:', error);
    ElMessage.error('文件加载失败: ' + error.message);
  }
};

getList();
</script>

<style scoped>
.preview-content {
  height: 70vh;
  overflow: auto;
}

.text-preview {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
  margin: 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.doc-preview {
  padding: 10px;
}

.excel-preview {
  padding: 10px;
}

.excel-preview :deep(table) {
  width: 100%;
  border-collapse: collapse;
}

.excel-preview :deep(td),
.excel-preview :deep(th) {
  border: 1px solid #dcdfe6;
  padding: 8px;
  text-align: left;
}

.excel-preview :deep(th) {
  background-color: #f5f7fa;
}

.image-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
}

.image-preview img {
  max-width: 100%;
  max-height: calc(70vh - 20px);
  object-fit: contain;
}

.unsupported-file {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}
</style>
